const fs = require('fs')
const path = require('path')
const https = require('https')

const MODELS = [
  'ssd_mobilenetv1_model-weights_manifest.json',
  'ssd_mobilenetv1_model-shard1',
  'face_landmark_68_model-weights_manifest.json',
  'face_landmark_68_model-shard1'
]

// 使用国内镜像
const BASE_URL = 'https://cdn.jsdelivr.net/gh/vladmandic/face-api/model/'
const MODEL_DIR = path.join(__dirname, '../models')

// 确保模型目录存在
if (!fs.existsSync(MODEL_DIR)) {
  fs.mkdirSync(MODEL_DIR, { recursive: true })
}

// 下载单个文件
const downloadFile = (url, dest) => {
  return new Promise((resolve, reject) => {
    const file = fs.createWriteStream(dest)
    https.get(url, response => {
      response.pipe(file)
      file.on('finish', () => {
        file.close()
        resolve()
      })
    }).on('error', err => {
      fs.unlink(dest, () => {})
      reject(err)
    })
  })
}

// 下载所有模型文件
async function downloadModels() {
  console.log('开始下载模型文件...')
  console.log('模型将被保存到:', MODEL_DIR)
  
  for (const model of MODELS) {
    const url = BASE_URL + model
    const dest = path.join(MODEL_DIR, model)
    
    console.log(`下载 ${model}...`)
    try {
      await downloadFile(url, dest)
      console.log(`${model} 下载完成`)
    } catch (error) {
      console.error(`下载 ${model} 失败:`, error)
      process.exit(1)
    }
  }
  
  console.log('所有模型文件下载完成')
}

downloadModels() 